package javango.contrib.jquery.widgets;

import java.util.HashMap;
import java.util.Map;

import javango.api.Settings;
import javango.contrib.hibernate.ModelChoiceField;
import javango.contrib.hibernate.ModelChoiceMap;
import javango.contrib.jquery.JqueryWidget;
import javango.contrib.jquery.Promptable;
import javango.forms.ValidationException;
import javango.forms.fields.BoundField;
import javango.forms.widgets.SelectWidget;
import javango.forms.widgets.Util;

import org.apache.commons.logging.LogFactory;

import com.google.inject.Inject;

public class JQuerySelectWidget<K,V> extends SelectWidget<K,V> implements JqueryWidget {

	public static final String JQUERY_BASEURL = "jquery_baseurl";
	public static final String SELECT_FIELD_MAX = "jquery_max_select_options";
	
	Settings settings;
	
	boolean smallList = true;
	
	// set to the max number of entries in a select field until it is replaced by the jquery version.
	Integer defaultMaxSelect;

	public String render(String name, Object value, java.util.Map<String,Object> attrs) {
		if (! (this.getChoices() instanceof ModelChoiceMap)) {
			return super.render(name, value, attrs);
		}
		
		int size = this.getChoices().size();

		if (size <= defaultMaxSelect) {
			return super.render(name, value, attrs);
		}
		
		smallList = false;
		
		Map<String, Object> finalAttrs = buildAttrs(attrs);
		finalAttrs.put("type", "text");
		finalAttrs.put("name", name);
		
		if (finalAttrs.containsKey("id")) {
			finalAttrs.put("id", String.format((String)finalAttrs.get("id"), name));
		}
		
		if (value != null) {
			if (value instanceof String) {
				if (!"".equals(value)) {
					finalAttrs.put("value" , value);
				}				
			} else if (value instanceof String[]){
				String[] values = (String[])value;
				if (values.length > 0 && !"".equals(values[0])) {
					finalAttrs.put("value", values[0]);
				}	
			} else {
				finalAttrs.put("value", value.toString());
			}
		}
			
		return String.format("<input%1$s />",
				Util.flatatt(finalAttrs)); 			// 1
	}
	
	public String getScript(BoundField field) {	
		if (smallList) {
			return ""; //
		}
		
		if (!field.getField().isEditable()) {
			return "";
		}
		
		if (field.getField() instanceof ModelChoiceField) {
			ModelChoiceField modelChoiceField = (ModelChoiceField) field.getField();
			Class model = modelChoiceField.getModel();
			Promptable p = (Promptable)model.getAnnotation(Promptable.class);
			if (p == null) {
				LogFactory.getLog(JQuerySelectWidget.class).error("Unsupported class " + model.getCanonicalName() );
				return "<!-- Unsupported class " + model.getCanonicalName() + " -->";
			}
			//////
			
			
			Object v = null;
			// try to lookup the object based on the key
			try {
				Object fieldValue = field.getValue();
				if (fieldValue instanceof String[]) {
					fieldValue = ((Object[])fieldValue)[0];
				}
				v = fieldValue == null ? null : field.getField().clean(fieldValue.toString(), new HashMap<String, String>());
			} catch (ValidationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			String jqueryUrl = settings.get(JQUERY_BASEURL);
			return String.format(
					// hide the primary key field, create the display field and prompt icon
					"$('#id_%1$s').javangoSelectWidget('%2$s','%3$s','%4$s','%5$s');\n",
					field.getHtmlName(),									// 1 (this is not correct..)
					modelChoiceField.getModel().getCanonicalName(),			// 2
					v == null ? "" : v.toString(),							// 3
					jqueryUrl,												// 4
					settings.get("jquery_media_url")); 						// 5
		}
		return "";
	}

	@Inject
	public JQuerySelectWidget(Settings settings) {
		super();
		this.settings = settings;

		defaultMaxSelect = settings.getAsInteger(SELECT_FIELD_MAX, 100);
	}

}
